package com.example.annotatedclass;


import cn.hutool.core.util.StrUtil;
import com.example.annotations.ConvertTargetField;
import com.sun.tools.javac.code.Symbol;

import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.MirroredTypeException;

/**
 * ConvertTargetField被注解标注的字段
 */
public class FieldAnnotatedBean {

    /**
     * target field name
     */
    private String name;
    /**
     * target field type
     */
    private String type;
    /**
     * type class qualified name
     */
    private String qualifiedTypeClassName;

    public FieldAnnotatedBean(Element field) throws IllegalArgumentException {

        ConvertTargetField fieldAnnot = field.getAnnotation(ConvertTargetField.class);
        name = fieldAnnot.name();

        if (StrUtil.isEmpty(name) ) {//&& field.asType().getKind().isPrimitive()
            throw new IllegalArgumentException(
                    String.format("name() in @%s for field %s is null or empty! that's not allowed",
                            ConvertTargetField.class.getSimpleName(), field.getSimpleName().toString()));
        }

        // Get the full QualifiedTypeName
        try {
            Class<?> clazz = fieldAnnot.type();
            type = clazz.getSimpleName();
        } catch (MirroredTypeException mte) {
            DeclaredType classTypeMirror = (DeclaredType) mte.getTypeMirror();
            TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
            qualifiedTypeClassName = classTypeElement.getQualifiedName().toString();
            type = classTypeElement.getSimpleName().toString();
        }
        if(type.equals(Object.class.getSimpleName())){
            type = ((Symbol.VarSymbol)field).type.tsym.getSimpleName().toString();
            qualifiedTypeClassName = ((Symbol.VarSymbol)field).type.tsym.getQualifiedName().toString();
        }

    }




    /**
     * 获取在{@link ConvertTargetField#name()}中指定的id
     * return the id
     */
    public String getName() {
        return name;
    }




    /**
     * 获取在 {@link ConvertTargetField#type()} 中指定的类型的简单名字
     *
     * @return qualified name
     */
    public String getTypeName() {
        return type;
    }

    public String getQualifiedTypeClassName() {
        return qualifiedTypeClassName;
    }

    public void setQualifiedTypeClassName(String qualifiedTypeClassName) {
        this.qualifiedTypeClassName = qualifiedTypeClassName;
    }
}
